<template>
  <el-drawer
    v-model="drawerVisible"
    title="公文模板设计器"
    direction="ltr"
    size="100%"
    @close="handleClose"
  >
    <template #header="{ titleId }">
      <div class="flex items-center justify-start w-full gap-3">
        <!-- 标题 -->
        <h1 :id="titleId" class="text-xl font-semibold text-gray-900 dark:text-gray-100">公文模板设计器</h1>

        <!-- 输入框 -->
        <el-input
          v-model="form.name"
          placeholder="请输入模板名称"
          class="w-60"
          clearable
        />

        <!-- 保存按钮 -->
        <el-button type="primary" @click="handleSave" :loading="loading">
          保存
        </el-button>
      </div>
    </template>

    <div v-loading="loading" class="relative min-h-50 p-5">
      <div class="w-full h-screen bg-slate-100 overflow-hidden">
        <div class="h-full grid grid-cols-12 gap-4 p-4">
          <!-- 左：配置 -->
          <div class="col-span-4 bg-white shadow !p-[30px] overflow-auto">
            <div class="flex items-center justify-between mb-3 ">
              <div class="text-lg font-semibold">自定义模板</div>
              <div class="flex items-center gap-2">
                <input ref="inputRef" type="file" accept="application/json" class="hidden" @change="onImportJSON" />
                <ElButton type="default" size="small" @click="triggerImport">导入JSON</ElButton>
                <ElButton type="success" size="small" @click="exportJSON">导出JSON</ElButton>
                <ElButton type="primary" size="small" @click="exportHTML">导出HTML</ElButton>
              </div>
            </div>

            <!-- 版头 -->
            <div class="flex items-center justify-between">
              <span class="text-base font-medium">版头要素：</span>
              <ElSwitch v-model="cfg.header.show" />
            </div>

            <div class="mt-3 space-y-4 bg-slate-50 rounded-xl p-4" v-if="cfg.header.show">
              <div class="grid grid-cols-12 gap-3 items-center">
                <div class="col-span-3 text-slate-600">发文机关标志：</div>
                <ElSelect v-model="cfg.header.organLabelFont" class="col-span-4">
                  <ElOption v-for="f in fontFamilies" :key="f" :value="f" :label="f" />
                </ElSelect>
                <ElSelect v-model="cfg.header.organLabelSize" class="col-span-3">
                  <ElOption v-for="s in chineseSizes" :key="s" :value="s" :label="s" />
                </ElSelect>
                <ElColorPicker class="col-span-2" v-model="cfg.header.organLabelColor" :predefine="preColors" />
              </div>

              <ElInput v-model="cfg.header.organLabel" placeholder="发文机关标志" />

              <!-- 自定义行 -->
              <div class="flex items-center gap-3">
                <ElButton link type="primary" @click="addHeaderLine">＋ 增加</ElButton>
                <span class="text-slate-400 text-sm">（在标志下方追加一行文本）</span>
              </div>
              <div v-for="(line, i) in cfg.header.extraLines" :key="i" class="flex items-center gap-2">
                <ElInput v-model="cfg.header.extraLines[i]" placeholder="自定义行内容" />
                <ElButton text type="danger" @click="removeHeaderLine(i)">删除</ElButton>
              </div>

              <div>
                <ElCheckbox v-model="cfg.header.showDocNo">份号</ElCheckbox>
                <ElCheckbox v-model="cfg.header.showUrgency">紧急程度</ElCheckbox>
                <ElCheckbox v-model="cfg.header.showDocCode">发文字号</ElCheckbox>
                <ElCheckbox v-model="cfg.header.showSigner">签发人</ElCheckbox>
                <ElCheckbox v-model="cfg.header.showSplitLine">版头分割线</ElCheckbox>
              </div>
            </div>

            <ElDivider />

            <!-- 正文：标题 / 正文 -->
            <div class="grid grid-cols-2 gap-6">
              <div>
                <div class="text-slate-500 mb-2">标题</div>
                <StyleRow v-model="cfg.title" :font-families="fontFamilies" :chinese-sizes="chineseSizes" :line-heights="[1,1.1,1.2]" :show-line-height="false" />
              </div>
              <div>
                <div class="text-slate-500 mb-2">正文</div>
                <StyleRow v-model="cfg.body" :font-families="fontFamilies" :chinese-sizes="chineseSizes" :line-heights="lineHeights" :show-line-height="true" />
              </div>
            </div>

            <!-- 各级标题 -->
            <div class="mt-6 grid grid-cols-2 gap-6">
              <div>
                <ElCheckbox v-model="cfg.h1.show">一级标题</ElCheckbox>
                <div class="mt-2"><StyleRow v-model="cfg.h1" :font-families="fontFamilies" :chinese-sizes="chineseSizes" /></div>
              </div>
              <div>
                <ElCheckbox v-model="cfg.h2.show">二级标题</ElCheckbox>
                <div class="mt-2"><StyleRow v-model="cfg.h2" :font-families="fontFamilies" :chinese-sizes="chineseSizes" /></div>
              </div>
              <div>
                <ElCheckbox v-model="cfg.h3.show">三级标题</ElCheckbox>
                <div class="mt-2"><StyleRow v-model="cfg.h3" :font-families="fontFamilies" :chinese-sizes="chineseSizes" /></div>
              </div>
              <div>
                <ElCheckbox v-model="cfg.h4.show">四级标题</ElCheckbox>
                <div class="mt-2"><StyleRow v-model="cfg.h4" :font-families="fontFamilies" :chinese-sizes="chineseSizes" /></div>
              </div>
            </div>

            <ElDivider />

            <!-- 版记 -->
            <div class="flex items-center justify-between">
              <span class="text-base font-medium">版记要素：</span>
              <ElSwitch v-model="cfg.imprint.show" />
            </div>
            <div class="mt-3 space-y-3 bg-slate-50 rounded-xl p-4" v-if="cfg.imprint.show">
              <div class="grid grid-cols-3 gap-3">
                <ElSelect v-model="cfg.imprint.font"><ElOption v-for="f in fontFamilies" :key="f" :label="f" :value="f" /></ElSelect>
                <ElSelect v-model="cfg.imprint.size"><ElOption v-for="s in chineseSizes" :key="s" :label="s" :value="s" /></ElSelect>
              </div>
              <div class="flex items-center gap-8 flex-wrap">
                <ElCheckbox v-model="cfg.imprint.showMainSend">主送机关</ElCheckbox>
                <ElCheckbox v-model="cfg.imprint.showCopySend">抄送机关</ElCheckbox>
                <ElCheckbox v-model="cfg.imprint.showIssuing">印发机关&印发日期</ElCheckbox>
              </div>
              <div class="grid grid-cols-2 gap-3">
                <ElInput v-if="cfg.imprint.showMainSend" v-model="cfg.imprint.mainSend" placeholder="主送机关" />
                <ElInput v-if="cfg.imprint.showCopySend" v-model="cfg.imprint.copySend" placeholder="抄送机关" />
              </div>
              <div class="grid grid-cols-2 gap-3" v-if="cfg.imprint.showIssuing">
                <ElInput v-model="cfg.imprint.issuingAgency" placeholder="印发机关" />
                <ElInput v-model="cfg.imprint.issuingDate" placeholder="印发日期" />
              </div>
            </div>
          </div>

          <!-- 右：预览 -->
          <div class="col-span-8 overflow-auto">
            <div :style="pageStyle">
              <!-- 版头预览 -->
              <template v-if="cfg.header.show">
                <table style="width:100%"><tbody>
                  <tr v-if="cfg.header.showDocNo"><td style="padding:0; font-family:黑体; font-size:16pt;">{{ cfg.header.docNo }}</td></tr>
                  <tr v-if="cfg.header.showUrgency"><td style="padding:0; font-family:黑体; font-size:16pt;">{{ cfg.header.urgency }}</td></tr>
                  <tr><td style="padding:0; line-height:28pt;">&nbsp;</td></tr>
                  <tr><td style="padding:0; line-height:28pt;">&nbsp;</td></tr>
                  <tr><td :style="organLabelStyle"><strong>{{ cfg.header.organLabel }}</strong></td></tr>
                  <tr v-for="(line, i) in cfg.header.extraLines" :key="i">
                    <td :style="organLabelStyle"><strong>{{ line }}</strong></td>
                  </tr>
                </tbody></table>

                <table v-if="cfg.header.showDocCode || cfg.header.showSigner" style="width:100%"><tbody>
                  <tr><td style="padding:0;">&nbsp;</td></tr>
                  <tr><td style="padding:0;">&nbsp;</td></tr>

                  <tr v-if="cfg.header.showDocCode && cfg.header.showSigner">
                    <td style="text-indent:1em; font-family:仿宋_GB2312; text-align:left; padding:0; font-size:16pt;"
                        :style="cfg.header.showSplitLine ? 'border-bottom:3pt solid #ff0000' : ''">
                      {{ cfg.header.leftCode }}
                    </td>
                    <td style="text-indent:1em; font-family:仿宋_GB2312; text-align:right; padding:0; width:192pt; font-size:16pt;"
                        :style="cfg.header.showSplitLine ? 'border-bottom:3pt solid #ff0000' : ''">
                      <span style="padding-right:1em;">签发人：{{ cfg.header.signer }}</span>
                    </td>
                  </tr>

                  <tr v-else>
                    <td colspan="2" style="padding:0; font-family:仿宋_GB2312; font-size:16pt; text-align:center;"
                        :style="cfg.header.showSplitLine ? 'border-bottom:3pt solid #ff0000' : ''">
                      <template v-if="cfg.header.showDocCode">{{ cfg.header.leftCode }}</template>
                      <template v-else>签发人：{{ cfg.header.signer }}</template>
                    </td>
                  </tr>
                </tbody></table>

                <div class="my-6"></div>
              </template>

              <!-- 标题 -->
              <p :style="titleStyle"><strong>{{ cfg.title.text }}</strong></p>
              <p style="text-align:center; font-family:仿宋_GB2312; font-size:16pt; line-height:28pt; margin-block:0;"> </p>

              <!-- 正文示例 -->
              <h1 v-if="cfg.h1.show" :style="h1Style">一、{{ cfg.h1.text }}</h1>
              <p :style="pStyle">正文内容正文内容正文内容正文内容。这里用于预览样式效果。</p>

              <h2 v-if="cfg.h2.show" :style="h2Style"><strong>（一）{{ cfg.h2.text }}</strong></h2>
              <p :style="pStyle">正文内容正文内容正文内容。正文内容正文内容正文内容。</p>

              <h3 v-if="cfg.h3.show" :style="h3Style"><strong>1、{{ cfg.h3.text }}</strong></h3>
              <h4 v-if="cfg.h4.show" :style="h4Style"><strong>（1）{{ cfg.h4.text }}</strong></h4>
              <p :style="pStyle">&nbsp; 正文内容正文内容正文内容。</p>

              <!-- 落款 -->
              <div style="margin:0; text-align:right; font-family:仿宋_GB2312; color:#000; font-size:16pt;" :style="{ lineHeight: cfg.body.lineHeight }">
                <br/><br/>{{ cfg.signature.text }}
              </div>
              <div style="margin:0; word-break:break-all; text-align:right; font-family:仿宋_GB2312; color:#000; font-size:16pt;" :style="{ lineHeight: cfg.body.lineHeight }">
                {{ cfg.signature.date }}
              </div>

              <div class="my-6"></div>

              <!-- 版记 -->
              <div v-if="cfg.imprint.show" class="mt-4">
                <table style="width:100%"><tbody>
                  <tr><td colspan="2" style="padding:0 1em; border-top:3pt solid #000;"></td></tr>
                  <tr v-if="cfg.imprint.showMainSend"><td :style="imprintLabelStyle">主送：{{ cfg.imprint.mainSend }}</td></tr>
                  <tr v-if="cfg.imprint.showCopySend"><td :style="imprintLabelStyle">抄送：{{ cfg.imprint.copySend }}</td></tr>
                  <tr><td colspan="2" style="padding:0 1em; border-top:3pt solid #000;"></td></tr>
                  <tr v-if="cfg.imprint.showIssuing">
                    <td :style="imprintLabelStyle">印发机关：</td>
                    <td :style="{ ...imprintValueStyle, textAlign:'right' }">{{ cfg.imprint.issuingDate }}</td>
                  </tr>
                  <tr><td colspan="2" style="padding:0 1em; border-top:3pt solid #000;"></td></tr>
                </tbody></table>
              </div>

              <div class="my-6"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts" name="TemplateDrawer">
// ========== 导入声明 ==========
import {
  ElSwitch, ElSelect, ElOption, ElInput, ElCheckbox, ElDivider,
  ElMessage, ElColorPicker, ElButton
} from 'element-plus'
import StyleRow from './StyleRow.vue'
import { fetchList, addObj, getObj, putObj } from "/@/api/knowledge/aiWritter";
import { useMessage } from "/@/hooks/message";

// ========== 组件引用 ==========
const inputRef = ref<HTMLInputElement | null>(null)

// ========== 响应式数据 ==========
const drawerVisible = ref(false);
const loading = ref(false);

// 表单数据对象
const form = reactive({
  id: '', // 主键
  name: '', // 模板名称
  content: '', // 模板内容
  json: '' // 模板内容json
});

// ========== 事件定义 ==========
const emit = defineEmits<{
  refresh: [] // 刷新数据列表
}>();

/** 字体映射：显示名 → 字体栈 */
const FONT_STACKS = {
  '宋体': '宋体,宋体-简,宋体-繁,华文宋体,simsun,SimSun,STSong,serif',
  '仿宋体': '仿宋,FangSong,STFangsong,serif',
  '黑体': 'SimHei,sans-serif',
  '楷体': '楷体,楷体-简,楷体-繁,KaiTi,STKaiti,华文楷体,serif',
  '小标宋': '小标宋,FZXBSJW-GB1-0,小标宋,sans-serif',
  '仿宋_GB2312': '仿宋_GB2312',
  '楷体_GB2312': '楷体_GB2312',
  'Arial': 'arial,helvetica,sans-serif',
  'Times New Roman': 'times,serif',
  'Helvetica': 'helvetica,arial,sans-serif',
}
const fontFamilies = Object.keys(FONT_STACKS)
const toStack = (name: string) => (name && (FONT_STACKS as any)[name]) || name || 'serif'

/** 中文字号到 pt 映射 */
const SIZE_PT: Record<string, string> = {
  '初号': '44pt', '小初': '36pt',
  '一号': '26pt', '小一': '24pt',
  '二号': '22pt', '小二': '18pt',
  '三号': '16pt', '小三': '15pt',
  '四号': '14pt', '小四': '12pt',
  '五号': '10.5pt', '小五': '9pt',
  '六号': '7.5pt', '小六': '6.5pt',
  '七号': '5.5pt', '八号': '5pt'
}
const chineseSizes = Object.keys(SIZE_PT)
const lineHeights = [1, 1.2, 1.4, 1.5, 1.75, 2, '28pt']
const preColors = ['#ff0000', '#e53935', '#d32f2f', '#c62828', '#b71c1c', '#ef5350']

/** ===== 配置 ===== */
const cfg = reactive({
  header: {
    show: true,
    docNo: '000001',
    urgency: '特急',
    organLabel: '琛达信息',
    organLabelFont: '宋体',
    organLabelSize: '初号',
    organLabelColor: '#ff0000',
    showSplitLine: true,
    leftCode: '发文机关代字〔20××〕10号',
    signer: '××××',
    showDocNo: true,
    showUrgency: true,
    showDocCode: true,
    showSigner: true,
    useImage: false,
    imageUrl: '',
    /** 自定义追加行 */
    extraLines: [] as string[],
  },

  title: { text: '主体部分标题样式', font: '宋体', size: '二号', bold: true, italic: false, underline: false, align: 'center', indent: '0' },
  body:  { font: '仿宋_GB2312', size: '三号', lineHeight: '28pt', bold: false, italic: false, underline: false, align: 'left', indent: '2em' },
  h1:    { show: true, text: '一级标题样式', font: '黑体',        size: '三号', bold: true,  italic: false, underline: false, align: '左对齐', indent: '2em' } as any,
  h2:    { show: true, text: '二级标题样式', font: '楷体_GB2312', size: '三号', bold: true,  italic: false, underline: false, align: 'left', indent: '2em' },
  h3:    { show: true, text: '三级标题样式', font: '仿宋_GB2312', size: '三号', bold: false, italic: false, underline: false, align: 'left', indent: '2em' },
  h4:    { show: true, text: '四级标题样式', font: '仿宋_GB2312', size: '三号', bold: false, italic: false, underline: false, align: 'left', indent: '2em' },

  signature: { text: '发文机关署名', date: '2025年1月1日' },

  imprint: {
    show: true,
    font: '仿宋_GB2312',
    size: '四号',
    showMainSend: true,
    showCopySend: true,
    showIssuing: true,
    mainSend: '机关一、机关二、机关三、机关四、机关五、机关六、机关七',
    copySend: '机关一、机关二、机关三、机关四、机关五、机关六、机关七',
    issuingAgency: '印发机关：',
    issuingDate: '××××年××月××日印发'
  }
})

/** ===== 预览样式 ===== */
const pageStyle = computed(() => ({
  width: 'min(1100px, 92vw)',
  minHeight: '100vh',
  margin: '0 auto',
  padding: '48px 56px',
  background: '#fff',
  boxShadow: '0 10px 30px rgba(0,0,0,.12), 0 0 0 1px rgba(0,0,0,.06)',
  boxSizing: 'border-box' as const,
  color: '#000',
  fontFamily: toStack(cfg.body.font),
  fontSize: SIZE_PT[cfg.body.size] ?? '16pt',
  lineHeight: cfg.body.lineHeight
}))

const organLabelStyle = computed(() => ({
  paddingLeft: '16pt',
  color: cfg.header.organLabelColor,
  fontSize: SIZE_PT[cfg.header.organLabelSize],
  lineHeight: SIZE_PT[cfg.header.organLabelSize],
  textAlign: 'center' as const,
  textAlignLast: 'justify' as const,
  fontFamily: toStack(cfg.header.organLabelFont)
}))

function mkHeadingStyle(x:any){return{
  margin:'0', fontSize:SIZE_PT[x.size], fontFamily:toStack(x.font), textIndent:x.indent, padding:'0',
  lineHeight:cfg.body.lineHeight, color:'#000', fontWeight:x.bold?'700':'400',
  fontStyle:x.italic?'italic':'normal', textDecoration:x.underline?'underline':'none', textAlign:x.align as any
}}
const titleStyle = computed(()=>({margin:'0',padding:'0',textAlign:cfg.title.align as any,color:'#000',
  fontFamily:toStack(cfg.title.font),fontSize:SIZE_PT[cfg.title.size],lineHeight:1.25,
  fontWeight:cfg.title.bold?'700':'400',fontStyle:cfg.title.italic?'italic':'normal',
  textDecoration:cfg.title.underline?'underline':'none',textIndent:cfg.title.indent}))
const h1Style = computed(()=>mkHeadingStyle(cfg.h1))
const h2Style = computed(()=>mkHeadingStyle(cfg.h2))
const h3Style = computed(()=>mkHeadingStyle(cfg.h3))
const h4Style = computed(()=>mkHeadingStyle(cfg.h4))
const pStyle  = computed(()=>({textIndent:cfg.body.indent,fontFamily:toStack(cfg.body.font),
  fontSize:SIZE_PT[cfg.body.size],color:'#000',lineHeight:cfg.body.lineHeight,marginBlockStart:'0',
  marginBlockEnd:'0',fontWeight:cfg.body.bold?'700':'400',fontStyle:cfg.body.italic?'italic':'normal',
  textDecoration:cfg.body.underline?'underline':'none',textAlign:cfg.body.align as any}))
const imprintTextStyle = computed(()=>({fontFamily:toStack(cfg.imprint.font),fontSize:SIZE_PT[cfg.imprint.size]??'14pt',lineHeight:'28pt',color:'#000'}))
const imprintLabelStyle = computed(()=>({paddingLeft:'1em',paddingRight:'1em',...imprintTextStyle.value}))
const imprintValueStyle = computed(()=>({paddingLeft:'1em',paddingRight:'1em',...imprintTextStyle.value}))

/** ===== 导入导出 ===== */
function download(filename: string, content: string, mime='application/octet-stream'){
  const blob = new Blob([content], {type: mime+';charset=utf-8'})
  const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = filename
  document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(a.href)
}
function exportJSON(){ download('govdoc-template.json', JSON.stringify(cfg,null,2), 'application/json'); ElMessage.success('已导出模板 JSON') }
function triggerImport(){ inputRef.value?.click?.() }
function onImportJSON(e:any){
  const file = e.target.files?.[0]; if(!file) return
  const reader = new FileReader()
  reader.onload = ()=>{
		try {
			Object.assign(cfg, JSON.parse(String(reader.result)));
			ElMessage.success('模板 JSON 已导入')
		} catch {
			ElMessage.error('导入失败：JSON 解析错误')
		} finally{ e.target.value='' } }
  reader.readAsText(file)
}

/** ===== 生成 HTML ===== */
function styleObj(obj: Record<string,string>){ return Object.entries(obj).map(([k,v])=>`${k.replace(/[A-Z]/g,m=>'-'+m.toLowerCase())}:${v};`).join('') }

function genHTML(): string {
  const style = `
@page { size: A4; margin: 2cm; }
html { background: transparent; }
body.doc-page { width:min(1100px,92vw); margin:0 auto; padding:5% 6%; box-sizing:border-box; background:#fff; color:#000;
  font-family:${toStack(cfg.body.font)}; font-size:${SIZE_PT[cfg.body.size]??'16pt'}; line-height:${cfg.body.lineHeight}; }
img{max-width:100%;height:auto;} p{margin:.8em 0;} table{border-collapse:collapse;width:100%;}
`.trim()

  const splitLine = cfg.header.showSplitLine ? 'border-bottom:3pt solid #ff0000;' : ''
  const bothHead = cfg.header.showDocCode && cfg.header.showSigner
  const onlyOne  = (cfg.header.showDocCode ? 1:0) + (cfg.header.showSigner?1:0) === 1

  const headerHTML = !cfg.header.show ? '' : `
<div class="bt_mb_header">
  <table style="width:100%"><tbody>
    ${cfg.header.showDocNo ? `<tr><td style="padding:0; font-family:${toStack('黑体')}; font-size:16pt;">${cfg.header.docNo}</td></tr>` : ''}
    ${cfg.header.showUrgency ? `<tr><td style="padding:0; font-family:${toStack('黑体')}; font-size:16pt;">${cfg.header.urgency}</td></tr>` : ''}
    <tr><td style="padding:0; line-height:28pt;">&nbsp;</td></tr>
    <tr><td style="padding:0; line-height:28pt;">&nbsp;</td></tr>
    <tr>
      <td style="padding-left:16pt; color:${cfg.header.organLabelColor}; font-size:${SIZE_PT[cfg.header.organLabelSize]};
                 line-height:${SIZE_PT[cfg.header.organLabelSize]}; text-align:center; text-align-last:justify;
                 font-family:${toStack(cfg.header.organLabelFont)};"><strong>${cfg.header.organLabel}</strong></td>
    </tr>
    ${cfg.header.extraLines.map(l => `
      <tr>
        <td style="padding-left:16pt; color:${cfg.header.organLabelColor}; font-size:${SIZE_PT[cfg.header.organLabelSize]};
                   line-height:${SIZE_PT[cfg.header.organLabelSize]}; text-align:center; text-align-last:justify;
                   font-family:${toStack(cfg.header.organLabelFont)};"><strong>${l}</strong></td>
      </tr>
    `).join('')}
  </tbody></table>

  ${(cfg.header.showDocCode || cfg.header.showSigner) ? `
  <table style="width:100%"><tbody>
    <tr><td style="padding:0;">&nbsp;</td></tr>
    <tr><td style="padding:0;">&nbsp;</td></tr>
    ${bothHead ? `
    <tr>
      <td style="text-indent:1em; font-family:${toStack('仿宋_GB2312')}; text-align:left; padding:0; font-size:16pt; ${splitLine}">
        ${cfg.header.leftCode}
      </td>
      <td style="text-indent:1em; font-family:${toStack('仿宋_GB2312')}; text-align:right; padding:0; width:192pt; font-size:16pt; ${splitLine}">
        <span style="padding-right:1em;">签发人：${cfg.header.signer}</span>
      </td>
    </tr>` : ''}

    ${onlyOne ? `
    <tr>
      <td colspan="2" style="padding:0; font-family:${toStack('仿宋_GB2312')}; font-size:16pt; ${splitLine}; text-align:center;">
        ${cfg.header.showDocCode ? cfg.header.leftCode : `签发人：${cfg.header.signer}`}
      </td>
    </tr>` : ''}

  </tbody></table>` : '' }
</div>
<div><br /><br /></div>`.trim()

  const mkInline = (x:any)=>`
style="margin:0;font-size:${SIZE_PT[x.size]};font-family:${toStack(x.font)};text-indent:${x.indent};padding:0;line-height:${cfg.body.lineHeight};
color:#000;font-weight:${x.bold?'700':'400'};font-style:${x.italic?'italic':'normal'};text-decoration:${x.underline?'underline':'none'};text-align:${x.align};"`

  const bodyHTML = `
<p style="margin:0;padding:0;text-align:${cfg.title.align};color:#000;font-family:${toStack(cfg.title.font)};font-size:${SIZE_PT[cfg.title.size]};
line-height:28pt;font-weight:${cfg.title.bold?'700':'400'};font-style:${cfg.title.italic?'italic':'normal'};text-decoration:${cfg.title.underline?'underline':'none'};
text-indent:${cfg.title.indent};"><strong>${cfg.title.text}</strong></p>
<p style="text-align:center;font-family:${toStack('仿宋_GB2312')};font-size:16pt;line-height:28pt;"> </p>

${cfg.h1.show?`<h1 ${mkInline(cfg.h1)}>一、${cfg.h1.text}</h1>`:''}
<p style="text-indent:${cfg.body.indent};font-family:${toStack(cfg.body.font)};font-size:${SIZE_PT[cfg.body.size]};
color:#000;line-height:${cfg.body.lineHeight};font-weight:${cfg.body.bold?'700':'400'};font-style:${cfg.body.italic?'italic':'normal'};
text-decoration:${cfg.body.underline?'underline':'none'};text-align:${cfg.body.align};">正文内容正文内容正文内容正文内容。这里用于预览样式效果。</p>

${cfg.h2.show?`<h2 ${mkInline(cfg.h2)}>（一）${cfg.h2.text}</h2>`:''}
<p style="text-indent:${cfg.body.indent};font-family:${toStack(cfg.body.font)};font-size:${SIZE_PT[cfg.body.size]};
color:#000;line-height:${cfg.body.lineHeight};font-weight:${cfg.body.bold?'700':'400'};font-style:${cfg.body.italic?'italic':'normal'};
text-decoration:${cfg.body.underline?'underline':'none'};text-align:${cfg.body.align};">正文内容正文内容正文内容。正文内容正文内容正文内容。</p>

${cfg.h3.show?`<h3 ${mkInline(cfg.h3)}>1、${cfg.h3.text}</h3>`:''}
${cfg.h4.show?`<h4 ${mkInline(cfg.h4)}>（1）${cfg.h4.text}</h4>`:''}

<p style="text-indent:${cfg.body.indent};font-family:${toStack(cfg.body.font)};font-size:${SIZE_PT[cfg.body.size]};color:#000;line-height:${cfg.body.lineHeight};">
  正文内容正文内容正文内容。
</p>

<div style="margin:0;text-align:right;font-family:${toStack('仿宋_GB2312')};color:#000;font-size:16pt;line-height:${cfg.body.lineHeight};"><br /><br />${cfg.signature.text}    </div>
<div style="margin:0;word-break:break-all;text-align:right;font-family:${toStack('仿宋_GB2312')};color:#000;font-size:16pt;line-height:${cfg.body.lineHeight};">${cfg.signature.date}    </div>
<p><br /><br /></p>
`.trim()

  const imprintTopRow = (cfg.imprint.showMainSend || cfg.imprint.showCopySend)
    ? `<tr><td style="padding-left:1em;padding-right:1em;${styleObj(imprintTextStyle.value)} border-top:3pt solid #000;border-bottom:2pt solid #000;" colspan="2">
         ${cfg.imprint.showMainSend ? '主送：'+cfg.imprint.mainSend : ''}${cfg.imprint.showMainSend&&cfg.imprint.showCopySend ? '<br>' : ''}${cfg.imprint.showCopySend ? '抄送：'+cfg.imprint.copySend : ''}
       </td></tr>` : ''
  const imprintBottomRow = cfg.imprint.showIssuing ? `
    <tr>
      <td style="padding-left:1em;${styleObj(imprintTextStyle.value)} border-bottom:3pt solid #000;">${cfg.imprint.issuingAgency}</td>
      <td style="padding-right:1em;text-align:right;${styleObj(imprintTextStyle.value)} border-bottom:3pt solid #000;">${cfg.imprint.issuingDate}</td>
    </tr>` : ''

  return `
<!doctype html><html><head><meta charset="utf-8" /><title>公文</title><style>${style}</style></head>
<body class="doc-page">
${headerHTML}
${bodyHTML}
${cfg.imprint.show ? `<div class="bt_mb_footer"><table style="width:100%;"><tbody>${imprintTopRow}${imprintBottomRow}</tbody></table></div><div><br /><br /></div>` : ''}
</body></html>`.trim()
}

/** ====== 对外：返回 HTML ====== */
/** 返回 HTML。默认仅 body 内容；传 {bodyOnly:false} 可返回完整文档 */
function getHtml(options?: { bodyOnly?: boolean }) {
  const full = genHTML()
  const body = full.match(/<body.*?>([\s\S]*?)<\/body>/i)?.[1] ?? full
  return options?.bodyOnly === false ? full : body
}
const getJson = () => {
  return JSON.stringify(cfg)
}

/** 便捷方法 */
function getBodyHtml(){ return getHtml({ bodyOnly: true }) }
function getFullHtml(){ return getHtml({ bodyOnly: false }) }

const setJson = (json:string) => {
  Object.assign(cfg, JSON.parse(String(json)));
}

/** 导出 HTML：复用 getHtml() */
function exportHTML(){
  const bodyHTML = getBodyHtml()
  download('govdoc.html', bodyHTML, 'text/html')
  ElMessage.success('已导出 HTML')
}

/** 自定义行 */
function addHeaderLine(){ cfg.header.extraLines.push('') }
function removeHeaderLine(i:number){ cfg.header.extraLines.splice(i,1) }

// ========== 方法定义 ==========
/**
 * 打开抽屉
 * @param id 模板ID，为空表示新建
 */
const openDrawer = (id: string) => {
  drawerVisible.value = true;
  // 重置表单数据
  form.id = '';
  form.content = '';
  form.name = '';
  form.json = '';

  // 获取AiDocumentTemplate信息
  if (id) {
    form.id = id;
    getAiDocumentTemplateData(id);
  }
};

/**
 * 关闭抽屉
 */
const handleClose = () => {
  drawerVisible.value = false;
  // 重置表单数据
  form.id = '';
  form.content = '';
  form.name = '';
  form.json = '';
};

/**
 * 保存模板
 */
const handleSave = () => {
  form.json = getJson();
  form.content = getHtml();

  if (!form.name) {
    useMessage().error('模板名称不能为空');
    return;
  }

  if (!form.content) {
    useMessage().error('模板内容不能为空');
    return;
  }

  loading.value = true;

  try {
    if (form.id) {
      // 更新
      putObj(form).then(() => {
        useMessage().success('保存成功');
        drawerVisible.value = false;
        emit('refresh');
      });
    } else {
      // 新增
      addObj(form).then(() => {
        useMessage().success('保存成功');
        drawerVisible.value = false;
        emit('refresh');
      });
    }
  } catch (error) {
    useMessage().error('保存失败');
  } finally {
    loading.value = false;
  }
};

/**
 * 获取详情数据
 * @param id 模板ID
 */
const getAiDocumentTemplateData = async (id: string) => {
  try {
    loading.value = true;
    const { data } = await getObj({ id: id });
    // 直接将第一条数据赋值给表单
    Object.assign(form, data[0]);
    // 设置模板内容json
    setJson(form.json);
  } catch (error) {
    useMessage().error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// ========== 暴露方法 ==========
defineExpose({
  openDrawer,
  getHtml,
  getBodyHtml,
  getFullHtml,
  getJson,
  setJson
})
</script>

<style>
html::-webkit-scrollbar { display: none; }
html { scrollbar-width: none; }

/* 抽屉样式 */
:deep(.el-drawer__header) {
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

:deep(.el-drawer__body) {
  padding: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .w-60 {
    width: 200px;
  }
}
</style>
